﻿using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;

namespace RuoVea.ExUtil.Validate;

/// <summary>
/// 描 述：自定义规则
/// </summary>
public sealed class MyRegexAttribute : ValidationAttribute
{
    string _pattern = string.Empty;

    /// <summary>
    /// 自定义规则
    /// </summary>
    /// <param name="pattern"></param>
    /// <param name="msg"></param>
    public MyRegexAttribute(string pattern, string msg)
    {
        _pattern = pattern;
        this.ErrorMessage = msg;
    }

    /// <summary>
    /// 证请求结果
    /// </summary>
    /// <param name="value">校验内容</param>
    /// <param name="validationContext">报错指定对象</param>
    /// <returns>证请求结果的容器</returns>
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (_pattern.IsNullOrWhiteSpace()) return new ValidationResult("表达式不能为空");

        if (value != null)
        {
            Regex r = new Regex(_pattern);
            if (!r.IsMatch(value + ""))
            {
                var errorMessage = FormatErrorMessage(validationContext.DisplayName);
                return new ValidationResult(errorMessage);
            }
        }
        return ValidationResult.Success;
    }
}
